<template>
  <div v-loading="dataLoading || optionsLoading" class="app-container">
    <div class="data-content">
      <div class="action-content">
        <el-row :gutter="10">
          <el-col :span="14">
            <span style="font-size: x-large; margin-right: 10px">{{ $t('boxShelve') }}</span>
            <span style="color: grey">{{ $t('shelve.orderNo') }} {{ orderInfo.orderNo }}</span>
          </el-col>
          <el-col :span="9">
            <el-button :disabled="currentTab === '1' || selectedList.length === 0" type="primary" style="float: right" @click="confirmShelve">{{ $t('shelve.confirm') }}</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="10" style="margin-top: 10px">
          <el-col :span="24">
            <el-input ref="boxNoInput" v-model="boxNo" :placeholder="$t('shelve.pleaseScanBoxNo')" clearable @keyup.enter.native.prevent="handleScanBox">
              <i slot="prefix" class="el-icon-full-screen scan-icon" />
            </el-input>
          </el-col>
        </el-row>
      </div>
      <el-tabs v-model="currentTab" @tab-click="handleTabSwitch">
        <el-tab-pane :label="$t('shelve.statusNew')" name="0" />
        <el-tab-pane :label="$t('shelve.statusFinished')" name="1" />
      </el-tabs>
      <div class="table-content">
        <el-table ref="mainTable" :data="tableData" height="100%" style="width: 100%" stripe highlight-current-row @selection-change="handleSelectionChange" @current-change="handleCurrentChange">
          <el-table-column v-if="currentTab === '0'" type="selection" width="55" align="center" />
          <el-table-column :label="$t('shelve.boxNo')" min-width="150" prop="boxNo" align="center" />
          <el-table-column :label="$t('shelve.realSize')" min-width="150" prop="realSize" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.boxLength }}*{{ scope.row.boxWidth }}*{{ scope.row.boxHeight }} CM</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('shelve.realWeight')" prop="realWeight" min-width="100" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.boxWeight }} KG</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('shelve.forecastNum')" prop="boxPreNum" min-width="100" align="center" />
          <el-table-column :label="$t('shelve.skuForecastNum')" prop="skuForecastNum" min-width="100" align="center">
            <template slot-scope="scope">
              <el-row v-for="(sku, i) in scope.row.orderInfoBoxSkuDTOList" :key="i" :gutter="5" style="margin-bottom: 2px">
                <span>{{ sku.skuCode }} * {{ sku.preSkuNum }}</span>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column prop="locationCode" min-width="250" align="center">
            <template slot="header">
              <span v-if="currentTab === '0'" style="color: red">*</span>{{ $t('shelve.locationAndNum') }}
            </template>
            <template slot-scope="scope">
              <span v-if="currentTab === '1'">{{ scope.row.locationCode }}</span>
<!--              <el-select v-else v-model="scope.row.locationCode" filterable :filter-method="filterBoxLocation" clearable @focus="boxLocationFocus">-->
<!--                <el-option v-for="item in boxLocationOptions" :key="item.value" :value="item.value" :label="item.value">-->
<!--                  <span style="float: left">{{ item.value }}</span>-->
<!--                  <span style="float: right; color: #8492a6; font-size: 13px">{{ $t('locationLang.' + item.label) }}</span>-->
<!--                </el-option>-->
<!--              </el-select>-->
              <el-input v-else v-model="scope.row.locationCode" />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { confirmShelve, getOrderInfo } from '@/api/business/warehouseManage/shelve';
import { scanFail, scanSuccess } from '@/utils/validate';
import { locationPickTypeDict, packageTypeDict } from '@/utils/dictData';
import { getDictOptionList, getTitleByValue } from '@/utils/dictUtils';
import { getDepotLocationForFree } from '@/api/business/depotManage/location';

export default {
  name: 'BoxShelve',
  components: {},
  data() {
    return {
      dataLoading: false,
      optionsLoading: false,
      currentTab: '0',
      orderInfo: {},
      boxNo: null,
      packagingTypeEnum: getDictOptionList(packageTypeDict),
      currentBox: null,
      tableData: [],
      selectedList: [],
      locationList: [],
      boxLocationOptions: [],
    }
  },
  created() {
    this.getDepotLocationForFree()
    this.getOrderInfo(this.$route.params.orderNo)
  },
  methods: {
    handleTabSwitch() {
      this.dataLoading = true
      this.tableData = this.orderInfo.orderInfoBoxDTOList.filter(item => {
        if (this.currentTab === '0') {
          return item.boxStatus === 1
        } else {
          return item.boxStatus !== 1
        }
      })
      if (this.currentTab === '0') {
        const selectedListTemp = this.selectedList;
        const currentBoxTemp = this.currentBox;
        this.$nextTick(() => {
          selectedListTemp.forEach(row => this.$refs.mainTable.toggleRowSelection(row, true))
          this.$refs.mainTable.setCurrentRow(currentBoxTemp);
          this.dataLoading = false
        })
      } else {
        this.dataLoading = false
      }
    },
    scrollToCurrentRow() {
      this.$nextTick(() => {
        const currentRow = this.$refs.mainTable.$el.getElementsByClassName('current-row')[0]
        if (currentRow) {
          this.$refs.mainTable.bodyWrapper.scrollTo({ top: currentRow.offsetTop, behavior: 'smooth' })
        }
      })
    },
    handleCurrentChange(currentRow, oldCurrentRow) {
      if (this.currentTab === '0') {
        this.currentBox = currentRow
      }
    },
    handleScanBox() {
      this.currentBox = this.orderInfo.orderInfoBoxDTOList.find(item => item.boxStatus === 1 && item.boxNo === this.boxNo)
      if (this.currentBox) {
        scanSuccess()
        this.currentTab = '0'
        this.selectedList.push(this.currentBox)
        this.handleTabSwitch();
        this.$nextTick(() => {
          this.scrollToCurrentRow()
        })
      } else {
        scanFail()
      }
      this.boxNo = null
      this.$refs.boxNoInput.focus()
    },
    handleSelectionChange(rows) {
      if (this.currentTab === '0') {
        this.selectedList = rows;
      }
    },
    async getOrderInfo(orderNo) {
      this.dataLoading = true;
      await getOrderInfo({ number: orderNo }).then((res) => {
        this.$refs.boxNoInput.focus()
        res.data.orderInfoBoxDTOList.forEach(box => {
          box.locationCode = ''
          if (box.orderInfoBoxSkuDTOList?.length > 0 && box.orderInfoBoxSkuDTOList[0].stockBatchList?.length > 0) {
            box.locationCode = box.orderInfoBoxSkuDTOList[0].stockBatchList[0].locationCode
          }
        })
        this.orderInfo = res.data;
        this.handleTabSwitch()
      }).finally(() => {
        this.dataLoading = false;
      })
    },
    async getDepotLocationForFree() {
      this.optionsLoading = true
      await getDepotLocationForFree({ freeFlag: 1, locationstatus: 1 }).then((res) => {
        this.locationList = res.data.resultList.map(item => {
          return { value: item.locationCode, label: getTitleByValue(getDictOptionList(locationPickTypeDict), item.pickType) }
        })
      }).finally(() => {
        this.optionsLoading = false;
      })
    },
    boxLocationFocus() {
      this.boxLocationOptions = this.locationList.slice(0, 10);
    },
    filterBoxLocation(value) {
      this.boxLocationOptions = this.locationList.filter(item => !value || item.value.toLowerCase().includes(value.toLowerCase())).slice(0, 10);
    },
    confirmShelve() {
      if (this.selectedList.length <= 0) return
      const request = {
        fromTerminal: 0,
        orderId: this.orderInfo.orderId,
        orderInfoForShelveList: []
      }
      for (const box of this.selectedList) {
        if (!box.locationCode) {
          this.$message.error(this.$t('pleaseCheck') + this.$t('required'))
          this.$refs.mainTable.setCurrentRow(box);
          this.scrollToCurrentRow()
          return
        }
        request.orderInfoForShelveList.push({
          boxId: box.boxId,
          locationCode: box.locationCode,
        })
      }
      this.dataLoading = true;
      confirmShelve(request).then((res) => {
        if (!res || res.returnCode !== 10000) return
        this.$confirm(this.$t('shelve.shelveSuccess'), '', {
          confirmButtonText: this.$t('shelve.continuScan'),
          cancelButtonText: this.$t('cancel'),
          type: 'success',
          center: true
        }).then(() => {
          this.$router.push({ name: 'ShelveScan' })
          this.confirmShelveSuccess()
        }).catch(() => {
          this.confirmShelveSuccess()
        });
      }).finally(() => {
        this.dataLoading = false;
      })
    },
    confirmShelveSuccess() {
      this.boxNo = null
      this.currentTab = '1'
      this.currentBox = null
      this.selectedList = []
      this.getOrderInfo(this.orderInfo.orderNo)
      this.getDepotLocationForFree()
      this.$nextTick(() => {
        this.$refs.mainTable.clearSelection();
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  position: absolute;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: auto;
}

.data-content{
  padding: 20px;
  flex: 1;
  border: 1px solid #e6ebf5;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  display: flex;
  flex-direction: column;
  min-height: 500px;
  overflow: hidden;

  .action-content {
    margin-bottom: 5px;

    ::v-deep .el-input__inner {
      height: 50px;
      padding-left: 45px;
    }

    .scan-icon {
      margin: 15px 15px 0 10px;
      font-size: 20px
    }
  }

  .table-content {
    flex: 1;
    overflow: hidden;
  }
}
</style>
